package com.lykj.llw.box.ui.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.View
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.LogUtils
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.databinding.ActCheckUpdateBinding
import com.lykj.llw.box.ui.diafrg.GEDownloadProgressDiaFrg
import com.yqwb.gamebox.internal.inter.OnDownloadListener
import me.jessyan.autosize.utils.AutoSizeUtils
import java.io.File
import java.io.FileNotFoundException

/**
 * ================================================
 * 检查更新
 * ================================================
 *
 * @author gosha
 * @date 2023/6/27-17:35
 */
class CheckUpdateActivity : BaseActivity() {
    lateinit var binding: ActCheckUpdateBinding

    var filePath: String = ""
    var fileName: String = ""

    var url: String = ""
    var title: String = ""
    var forceUpdate = false
    val downProgress = GEDownloadProgressDiaFrg()

    override fun onStart() {
        super.onStart()

        val layoutParams = window.attributes
        layoutParams.dimAmount = 0.75f
        layoutParams.gravity = Gravity.CENTER
        window.setLayout(
            AutoSizeUtils.dp2px(this, 215f),
            AutoSizeUtils.dp2px(this, 284f)
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActCheckUpdateBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun initUI() {
        forceUpdate = intent.getBooleanExtra("forcedUpdate", false)
        url = intent.getStringExtra("url") ?: ""
        title = intent.getStringExtra("title") ?: ""
        val content = intent.getStringExtra("content")
        binding.tvTitle.text = title
        binding.tvSubject.text = content
//
//        if (forceUpdate) {
//            binding.ivClose.visibility = View.GONE
//        } else {
//            binding.ivClose.visibility = View.VISIBLE
//        }
    }

    override fun initData() {
    }

    override fun setListener() {
//        binding.ivClose.clickWithTrigger {
//            finish()
//        }
        binding.tvBtnUpdate.clickWithTrigger {
            if (PackageUtils.canRequestPackageInstalls(this)) {
                downloadAndInstall()
            } else {
                PackageUtils.showSettingPackageInstall(this)
            }
        }
    }


    //下载并安装
    private fun downloadAndInstall() {
//        url = "http://10.0.1.204:8080/app-release.apk"
        filePath = getExternalFilesDir("apk")?.path ?: ""
        fileName = "${url.substring(url.lastIndexOf("/") + 1)}"
        if (filePath.isNullOrBlank() or fileName.isNullOrBlank()) {
            return
        }

        LogUtils.e("文件路径:${filePath}")
//            if (File("$filePath/$fileName").exists()) {
//                installApk("$filePath/$fileName")
//                return@setOnClickListener
//            }
        downProgress.show(supportFragmentManager, "下载进度弹窗")
        RetrofitManager.instance.downFile(url, filePath, fileName, object : OnDownloadListener {
            override fun onSuccess() {
                LogUtils.d("downFile:onSuccess")
                PackageUtils.installApk(this@CheckUpdateActivity, "$filePath/$fileName")
            }

            override fun onFail() {
                LogUtils.d("downFile:onFail")
                downProgress.dismissAllowingStateLoss()
                ToastUtils.showShort(this@CheckUpdateActivity, "下载失败,请重试")
            }

            override fun onProgress(currentBytes: Float, totalBytes: Float, progress: Int) {
                if (progress == 0) {
                    return
                }
                downProgress.setProgress(progress)
                if (progress == 100) {
                    downProgress.dismissAllowingStateLoss()
                }
            }
        })
    }
}